package app.softtech.freechat.adapter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import app.softtech.freechat.Constants;
import app.softtech.freechat.HttpRequest;
import app.softtech.freechat.R;
import app.softtech.freechat.app.AppController;
import app.softtech.freechat.database.DatabaseFriend;
import app.softtech.freechat.database.DatabaseHanler;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class FriendRequestAdapter extends BaseAdapter {
	private static final String TAG = FriendRequestAdapter.class.getSimpleName();

	// Fields
	private Activity mActivity;
	private LayoutInflater mInflater;
	private List<DatabaseFriend> mFriendList;
	ImageLoader imageLoader = AppController.getInstance().getImageLoader();
	
	private String mUserId;
	private String mRequestId;
	private String mFriendId;
	private String mRegId;
	private DatabaseHanler db;
	
	/**
	 * 
	 * @param activity
	 * @param friendList
	 */
	public FriendRequestAdapter(Activity activity, List<DatabaseFriend> friendList) {
		this.mActivity = activity;
		this.mFriendList = friendList;
		this.mRegId = this.mActivity.getSharedPreferences(Constants.PROJECT_PREFS, Context.MODE_PRIVATE).getString(Constants.PROPERTY_REG_ID, "");
		this.mUserId = this.mActivity.getSharedPreferences(Constants.PROJECT_PREFS, Context.MODE_PRIVATE).getString(Constants.USER_ID, "");
		this.db = new DatabaseHanler(mActivity);
	}

	@Override
	public int getCount() {
		return mFriendList.size();
	}

	@Override
	public Object getItem(int position) {
		return mFriendList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (mFriendList.size() == 0) {
			return convertView;
		}

		if (mInflater == null) {
			mInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.list_row_friend_request, parent, false);
		}

		if (imageLoader == null) {
			imageLoader = AppController.getInstance().getImageLoader();
		}

		NetworkImageView friendRequestAvatar = (NetworkImageView) convertView.findViewById(R.id.img_avatar);
		TextView friendRequestName = (TextView) convertView.findViewById(R.id.tv_friend_name);
		TextView friendRequestEmail = (TextView) convertView.findViewById(R.id.tv_friend_email);
		Button btnAcceptRequest = (Button) convertView.findViewById(R.id.btn_accept_friend_request);
		Button btnDeclineRequest = (Button) convertView.findViewById(R.id.btn_decline_friend_request);

		DatabaseFriend df = mFriendList.get(position);

		friendRequestAvatar.setImageUrl(df.getFriend_Avatar(), imageLoader);
		friendRequestName.setText(df.getFriend_Name());
		friendRequestEmail.setText(df.getFriend_Status());
		
		mFriendId = String.valueOf(df.getFriend_id());
		mRequestId = String.valueOf(df.getRequestId());
		Log.i(TAG, mRequestId + " " + mFriendId);
		
		ButtonOnClickListener listener = new ButtonOnClickListener(position);
		btnAcceptRequest.setOnClickListener(listener);
		btnDeclineRequest.setOnClickListener(listener);

		return convertView;
	}

	class ButtonOnClickListener implements OnClickListener {
		private int mPosition;
		
		public ButtonOnClickListener(int position){
			this.mPosition = position;
		}

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_accept_friend_request:
				AcceptFriendRequest accept = new AcceptFriendRequest();
				accept.execute();
				mFriendList.remove(mPosition);
				notifyDataSetChanged();
				Toast.makeText(mActivity, "Accept Friend Request " + mPosition, Toast.LENGTH_SHORT).show();
				break;
			case R.id.btn_decline_friend_request:
				DeclineFriendRequest decline = new DeclineFriendRequest();
				decline.execute();
				mFriendList.remove(mPosition);
				notifyDataSetChanged();
				Toast.makeText(mActivity, "Decline Friend Request " + mPosition, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	}
	
	/**
	 * Inner class used to accept friend request from other user
	 * @author LocDev
	 *
	 */
	class AcceptFriendRequest extends AsyncTask<Void, Void, JSONObject>{
//		private int mPosition;
//		public AcceptFriendRequest(int position){
//			this.mPosition = position;
//		}

		@Override
		protected JSONObject doInBackground(Void... params) {
			JSONObject jsonObj = acceptFriendRequest();
			return (jsonObj == null) ? null : jsonObj;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			if(result != null){
				//Do something here
				Log.i(TAG, mFriendId);
				
				db.updateDatabaseFriend(Integer.parseInt(mFriendId));
				db.close();
				Log.i(TAG, "Accept successfully!");
			} else {
				Log.i(TAG, "Accept failure!");
			}
		}
		
	}
	
	/**
	 * Inner class used to decline friend request from other user
	 * @author LocDev
	 *
	 */
	class DeclineFriendRequest extends AsyncTask<Void, Void, Boolean>{

		@Override
		protected Boolean doInBackground(Void... params) {
			return (declineFriendRequest() == false) ? false : true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result){
				//Do something here
				Log.i(TAG, "Decline successfully!");
				db.deleteFriendByRequestId(Integer.parseInt(mRequestId));
				db.close();
			} else {
				//And here
				Log.i(TAG, "Decline failure!");
			}
		}
	}
	
	/**
	 * 
	 * @param requestId
	 * @return null if accept failure or jsonObj if otherwise
	 */
	private JSONObject acceptFriendRequest(){
		Log.i(TAG, mFriendId);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Constants.USER_ID, mUserId));
		params.add(new BasicNameValuePair(Constants.USER_REQUEST_ID, mFriendId));
		params.add(new BasicNameValuePair(Constants.ID_REQUEST, mRequestId));
		params.add(new BasicNameValuePair(Constants.PROPERTY_REG_ID, mRegId));
		
		HttpRequest request = new HttpRequest();
		String result = request.makeServiceCall(Constants.URL_ACCEPT_FRIEND_REQUEST, HttpRequest.POST, params);
		if(!result.isEmpty()){
			JSONObject jsonObj;
			try {
				jsonObj = new JSONObject(result);
				return jsonObj;
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}
	
	/**
	 * 
	 * @param requestId
	 * @return true if decline successfully or false if otherwise
	 */
	private boolean declineFriendRequest(){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Constants.USER_ID, mUserId));
		params.add(new BasicNameValuePair(Constants.USER_REQUEST_ID, mFriendId));
		params.add(new BasicNameValuePair(Constants.ID_REQUEST, mRequestId));
		params.add(new BasicNameValuePair(Constants.PROPERTY_REG_ID, mRegId));
		
		HttpRequest request = new HttpRequest();
		String result = request.makeServiceCall(Constants.URL_DECLINE_FRIEND_REQUEST, HttpRequest.POST, params);
		
		if(!result.isEmpty()){
			try {
				JSONObject jsonObj = new JSONObject(result);
				String check = jsonObj.getString(Constants.KEY_SUCCESS);
				if(Integer.parseInt(check) != 0){
					return true;
				} else {
					return false;
				}
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}
}
